package com.woniuxy.consumer;

import com.rabbitmq.client.Channel;
import com.woniuxy.entity.Order;
import com.woniuxy.mapper.OrderMapper;
import com.woniuxy.util.RabbitmqConst;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @BelongsProject: pigTrotterStore
 * @BelongsPackage: com.woniuxy.consumer
 * @Author: Quan
 * @Date: 2025/3/21 10:31
 */
@Component
public class DelayConsumer {
	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	/**
	 * 延迟订单，判断订单状态，如果待付款（1），则修改成已取消（4）
	 *
	 * @param msg
	 * @param channel
	 * @param message
	 */
	@RabbitListener(queues = RabbitmqConst.CHECK_ORDER_STATUS_QUEUE)
	public void receive(String msg, Channel channel, Message message) {
		try {
			Order order = orderMapper.queryOrderByOrderNum(msg);
			if (redisTemplate.delete(order.getOrderNum())) {
				if (order.getStatus().equals(1)) {
					order.setOrderNum(msg);
					order.setStatus(4);
					orderMapper.updateOrderStatus(order);
				}

				channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
			}
		} catch (Exception e) {
			try {
				channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
			} catch (IOException ex) {
				throw new RuntimeException(ex);
			}
		}
	}
}
